module(..., package.seeall)

require "utils.misc"

initialized = false
env = MOAIEnvironment
viewport = {}
layer = {}
camera = {}
config = {}

function init(cfg)
    --[[
    Opens the window and creates the default viewport and layer.
    ]]
    if initialized then
        print("WARNING: Application is already initialized.")
    end
    printf("INFO: Starting up on: %s version: %s\n", env.osBrand, env.osVersion)
    config.width  = cfg.width  or env.horizontalResolution or 800
    config.height = cfg.height or env.verticalResolution   or 600
    config.title  = cfg.title  or "Untitled MOAI-X window"
    MOAISim.openWindow(config.title, config.width, config.height)
    initialized = true
end

function add_viewport(sx, sy, name)
    --[[
    Creates a new viewport and adds it to the App.viewport table.
    ]]
    name = name or "default"
    if viewport[name] ~= nil then
        error(string.format("viewport name already in use - %s", name), 2)
    end
    local v = MOAIViewport.new()
    v:setSize(config.width, config.height)
    v:setScale(sx or 1, sy or 0)
    viewport[name] = v
    return v
end

function add_ui_viewport(name)
    --[[
    Similar to add_viewport(), but sets up a viewport with a width and height of 1 unit, and 
    offsets its origin to the upper left corner of the viewport. Also, the y-axis is increases 
    downward, using a kind of normalized window-style coordinate system.
    ]]
    local v = add_viewport(1, -1, name)
    v:setOffset(-1, 1)  -- position the viewport's origin at its upper-left corner
    v.is_ui = true
    return v
end

function add_layer(viewport, name)
    --[[
    Creates a new layer and sets its viewport. The layer is added to the App.layer table.
    ]]
    name = name or "default"
    if layer[name] ~= nil then
        error(string.format("layer name already in use - %s", name), 2)
    end
    local l = MOAILayer2D.new()
    l:setViewport(viewport)
    MOAIRenderMgr.pushRenderPass(l)
    layer[name] = l
    return l
end

function add_camera(layer, name)
    --[[
    Creates a new camera and attaches it to a layer. The camera is added to the App.camera table.
    ]]
    name = name or "default"
    if camera[name] ~= nil then
        error(string.format("camera name already in use - %s", name), 2)
    end
    local c = MOAICamera2D.new()
    layer:setCamera(c)
    camera[name] = c
    return c
end
